/**
 * Created by Administrator on 2017/9/4.
 */
define(function (require) {


    /***
     * 事件触发器
     * @returns {emit}
     * @constructor
     */
    function Emit() {
        var events = {};


        function emit() {

        }

        emit.prototype = {
            on: function (eventName, eventFn) {
                events[eventName] = events[eventName] || [];
                events[eventName].push(eventFn);
            },
            trigger: function (eventName, _) {
                for (var fn in events[eventName]) {
                    events[eventName][fn].apply(null, Array.prototype.slice.call(arguments, 1));
                }
            }
        }

        return new emit();
    }


    var $ = require("jquery");
    require("jquery.cookie");
    var userHandler = new require("userHandler").StudentHandler();
    var liveRoom = null;
    var mediaStream = null;
    var ws = require("webSocketChannel");


    function LiveClient() {


    }

    LiveClient.prototype = new Emit();
    LiveClient.prototype.requestReceive = requestReceive;
    LiveClient.prototype.start = function () {

        var that = this;
        userHandler.getCourse($.cookie("courseId"), function (data) {

            liveRoom = require("liveRTC").RtcClient({
                name: $.cookie("username"),
                videoSourceName: data.teacherId
            });

            // 监测教师端直播的开启\关闭
            ws.addEventListener("message", function (e) {
                switch (e.data.type) {
                    case "live-open":
                        requestReceive.call(that);
                        break;
                    case "live-closed":
                        informClosed.call(that);
                        break;
                }
            });


            liveRoom.on("addstream", function (mediaStream) {
                console.log(mediaStream)
                that.trigger("open", mediaStream);
            });
            liveRoom.on('removestream',function () {
                console.log("stream removed");
                that.trigger('closed');
            })

            liveRoom.setWebSocketChannel(ws);

            requestReceive.call(that)


        })
    }

    function requestReceive() {

        if (ws.OPEN === ws.readyState) {
            console.log("Connecting")
            liveRoom.connect();
        } else {
            // 隔段时间再询问ws是否开启
            setTimeout(requestReceive.bind(this), 10);
        }

    }

    function informClosed() {

    }

    /**
     * 事件类型
     * 1.open
     * 2.closed
     */
    return new LiveClient();
})